package com.ms.p2p.controller.wap;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;
import com.ms.common.exception.NoticeException;
import com.ms.common.utils.AppContext;
import com.ms.common.utils.MsDateUtils;
import com.ms.common.utils.SpringContextHolder;
import com.ms.p2p.Constants;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.entity.FuyouBank;
import com.ms.p2p.entity.RetMap;
import com.ms.p2p.entity.UserThreadLocal;
import com.ms.p2p.entity.account.Account;
import com.ms.p2p.entity.account.AccountBank;
import com.ms.p2p.entity.account.Withdraw;
import com.ms.p2p.entity.member.Auth;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.enums.LoanStatus;
import com.ms.p2p.plugin.IPlugin;
import com.ms.p2p.plugin.payment.IPaymentEvent;
import com.ms.p2p.plugin.payment.PaymentPluginBundle;
import com.ms.p2p.plugin.validation.annotation.RequiredStringValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import com.ms.p2p.provider.*;
import com.ms.p2p.utils.TradeUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chensk on 2017/11/28.
 */
@Controller
@RequestMapping({ "/wap/member" })
public class WapMemberController extends  WapBaseController{

    @Autowired
    PaymentPluginBundle paymentPluginBundle;
    @Reference
    private MemberAccountBankProvider accountBankProvider;
    @Reference
    private LoanTenderRecordProvider loanTenderRecordProvider;
    @Reference
    private MemberAccountProvider account_Service;
    @Reference
    private MemberAccountBankProvider bankService;
    @Reference
    private CertiFiCationProvider certificationProvider;
    @Reference
    private MailAuthProvider mailAuthProvider;
    @Reference
    private LoanDueInProvider loanDueInProvider;
    @Reference
    private MemberAccountRechargeProvider rechargeService;
    @Reference
    private MemberProvider memberProvider;

    @Reference
    private PayMethodProvider payMethodProvider;
    @Reference
    private SettingProvider settingProvider;

    @Reference
    private YeahpaysProvider yeahpaysProvider;
    @Reference
    private SendProvider smsService;
    @Reference
    private MemberAccountRecordProvider logService;

    @Reference
    private IdCardQueryProvider idCardQueryProvider;

    @Reference
    RedPacketProvider redPacketProvider;
    @Reference
    MemberWithDrawProvider memberWithDrawProvider;
    @Reference
    FuyouProvider fuyouProvider;
    /**
     * 我的账户
     */
    @RequestMapping({""})
    public String index(Model model) {
        Member user = getCurrentUser();


        Auth realName = certificationProvider.findByUserId(user.getId());
        AccountBank bank = bankService.findByUserId(user.getId());
        Account account = account_Service.findByUserId(user.getId());

        List<Map<String, Object>> logs =
                logService.findPager(user.getId() + "", null, null, null, null, 0, 10);
        String income = loanDueInProvider.getIncome(user.getId(), 1);
        model.addAttribute("income", income);
        model.addAttribute("account", account);
        model.addAttribute("realName", realName);
        model.addAttribute("bank", bank);

        return "wap/me/index";

        }

    @RequestMapping(value = { "/redpacket/list" },method = RequestMethod.GET)

    public String redpacketlist(HttpServletRequest request, Integer currentPage, String status) {
        Member user =  UserThreadLocal.get();
        request.setAttribute("status",status);
        return  "/wap/me/redpacket";

    }
    @RequestMapping(value = { "/redpacket/list" },method = RequestMethod.POST)
    @ResponseBody
    public String list(HttpServletRequest request, Integer currentPage, String status) {
        Member user =  UserThreadLocal.get();
        PageBean page = new PageBean();
        page.setCurrentPage(currentPage);
        FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");
        String templatePath = Constants.TEMPLATE_REDPACKET_ITEM;
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = null;
        StringBuilder content = new StringBuilder();
        try {
            template = configuration.getTemplate(templatePath, "utf-8");
            HashMap loan = new HashMap();
                loan.put("reds", redPacketProvider.findPager(page,status,user.getId(),null));
                content.append(FreeMarkerTemplateUtils.processTemplateIntoString(template, loan));
        } catch (Exception e) {
            System.out.print(e);
            e.printStackTrace();
        }
        return  content.toString();
    }
    @RequestMapping("/invite")
    public String invite(
            HttpServletRequest request,
            HttpSession session ){
        Member loginUser = getCurrentUser();

        String phone = "";
        String member_phone = loginUser.getMember_phone();
        if (member_phone != null && !member_phone.equals("")) {
            phone = getBASE64(member_phone + "");
        }
        request.setAttribute("phone", phone);
        return "/wap/me/invite_friends";
    }


    /*
 *我的投资-还款中
 * */
    @RequestMapping(value = {"/loan/repaying"},method = RequestMethod.POST)
    @ResponseBody
    public String collection(HttpServletRequest request, PageBean page) throws Exception {
        Member user = getCurrentUser();
        page.getBegin();
        List<Map<String, Object>> loans = loanTenderRecordProvider.findLoanPager(user.getId(), LoanStatus.STATUS_9.getValue()+"",page);
        page.setTotalCount(loanTenderRecordProvider
                .findLoanCount(user.getId(),LoanStatus.STATUS_9.getValue()+""));

        FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");

        String templatePath = Constants.TEMPLATE_WAP_LOANS_ITEM;
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = null;
        StringBuilder content = new StringBuilder();
        try {
            template = configuration.getTemplate(templatePath, "utf-8");
            HashMap loan = new HashMap();
            if(loans.size()>0) {
                loan.put("loans", loans);
                content.append(FreeMarkerTemplateUtils.processTemplateIntoString(template, loan));
            }

        } catch (Exception e) {
            System.out.print(e);
            e.printStackTrace();
        }
     return  content.toString();
    }

    @RequestMapping({ "/loan" })
    public String loanlist(String type,Model model){
         model.addAttribute("type",type);
        return "/wap/me/invest";
    }
    /**
     * 我的投资-已还款
     */
    @RequestMapping(value = { "/loan/payed" },method = RequestMethod.POST)
    @ResponseBody
    public String payed(HttpServletRequest request,
                        HttpServletResponse response, HttpSession session) throws Exception {
        Member user = getCurrentUser();

        PageBean page = new PageBean();
        String currentPage = request.getParameter("currentPage");
        if (currentPage != null && !("".equals(currentPage))) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        List<Map<String, Object>> loans = loanTenderRecordProvider.findLoanPager(user.getId(), LoanStatus.STATUS_6.getValue()+"",page);
        page.setTotalCount(loanTenderRecordProvider
                .findLoanCount(user.getId(),LoanStatus.STATUS_6.getValue()+""));
        FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");

        String templatePath = Constants.TEMPLATE_WAP_LOANS_ITEM;
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = null;
        StringBuilder content = new StringBuilder();
        try {
            template = configuration.getTemplate(templatePath, "utf-8");
            HashMap loan = new HashMap();
            if(loans.size()>0) {
                loan.put("loans", loans);
                content.append(FreeMarkerTemplateUtils.processTemplateIntoString(template, loan));
            }

        } catch (Exception e) {
            System.out.print(e);
            e.printStackTrace();
        }


        return  content.toString();
    }



    /**
     * 收支明细
     */
    @RequestMapping(value = {"/account/log"},method = RequestMethod.GET)

    public String tolog(String logType,Model model){
        PageBean page = new PageBean();
        model.addAttribute("logType", logType);
        return "/wap/me/accountlog";
    }
    /**
     * 收支明细
     */
    @RequestMapping(value = {"/account/log"},method = RequestMethod.POST)
    @ResponseBody
    public String log(String logType, String beginDate, String endDate, String currentPage,Model model){
        PageBean page = new PageBean();
        if (StringUtils.isNotBlank(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        Member user = getCurrentUser();
        List<Map<String, Object>> logs =
                logService.findPager(user.getId() + "", null, logType, beginDate, endDate, page.getBegin(),
                        page.getPageSize());

        page.setTotalCount(logService.findCount(user.getId() + "", null,logType, beginDate, endDate));
        FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");

        String templatePath = Constants.TEMPLATE_WAP_ACCOUNT_LOG_ITEM;
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = null;
        StringBuilder content = new StringBuilder();
        try {
            template = configuration.getTemplate(templatePath, "utf-8");

            HashMap loan = new HashMap();
            loan.put("logs",logs);
            content.append(FreeMarkerTemplateUtils.processTemplateIntoString(template, loan));

        } catch (IOException e) {
            e.printStackTrace();
        }
        catch (TemplateException e) {
            e.printStackTrace();
        }

        return  content.toString();

    }


    /**
     * 提交提现申请
     */
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "money", message = "提现金额不能为空")

    }
    )
    @RequestMapping("/account/docash")
    @ResponseBody
    public Message submit(Double money) throws Exception {
        //验证码校验
        Member user = getCurrentUser();
        Account account = account_Service.findByUserId(user.getId());
        AccountBank banCard = bankService.findByUserId(user.getId());
        if (banCard == null) {
            return Message.error("请先绑定您的银行卡!") ;
        }
        if (banCard.getStatus() == 0) {
            return Message.error("为了防止恶意提现,请先使用该银行卡充值，才能提现!");
        }
        if (money < 100 || money > 50000) {
            return Message.error("单笔提现金额为100-50000元");
        }

        if (BigDecimal.valueOf(money).compareTo(account.getBalance()) > 0) {
            return Message.error("提现金额大于账户最大可用余额，请重新操作!");
        }
        Withdraw widthdraw = new Withdraw();
        widthdraw.setUser_id(user.getId());
        widthdraw.setTrade_no(TradeUtil.getTrano()+"");
        widthdraw.setTotal(new BigDecimal(money));
        widthdraw.setAddtime(MsDateUtils.getTime());
        widthdraw.setAddip(AppContext.getRemoteIp());
        widthdraw.setCrad_no(banCard.getBank_cardno());
        widthdraw.setBank(banCard.getBank());
        widthdraw.setBranch(banCard.getBranch());
        memberWithDrawProvider.withDrawApply(widthdraw, AppContext.getRemoteIp());
        return successMessage;
    }
    @RequestMapping({ "/waprecharge" })
    public String money(String money,HttpServletRequest request) throws Exception {
        Member user = getCurrentUser();
        List<IPlugin> plugins = paymentPluginBundle.getPluginList();

        for (IPlugin plugin : plugins) {
            if ("55".equals(plugin.getId())) {
                HashMap map = new HashMap();
                Auth auth = certificationProvider.findByUserId(user.getId());
                AccountBank bank = accountBankProvider.findByUserId(user.getId());
                if(auth == null)
                    return "尚未实名认证";
                if(bank ==null)
                    return "银行尚未认证";
                map.put("bank_card",bank.getBank_cardno());
                map.put("realname",auth.getReal_name());
                map.put("id_card_no",auth.getId_number());
                IPaymentEvent pay = (IPaymentEvent) plugin;
                return pay.onPay(user.getId(), new BigDecimal(money), map,request);
            }
        }
        return null;
    }

    /**
     * 我的账户
     */
    @RequestMapping({"/account/cash"})
    public String cash(Model model) {
        Member user = getCurrentUser();
        AccountBank bank = bankService.findByUserId(user.getId());
        Account account = account_Service.findByUserId(user.getId());
        model.addAttribute("bankCard", bank);
        model.addAttribute("account", account);
        return "wap/me/cash";

    }
    /**
     * 修改支付密码
     */
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "oldpass", message = "旧 密码不能为空"),
            @RequiredStringValidator(fieldName = "pass1", message = "就密码不能为空"),
            @RequiredStringValidator(fieldName = "pass2", message = "确认不能为空"),
            @RequiredStringValidator(fieldName = "type", message = "类型不能为空")

    })
    @RequestMapping("/pwdmodify")
    @ResponseBody
    public Message modifyPayPwd(String oldpass, String pass1, String pass2,String type) {
        Member member = getCurrentUser();
        member = memberProvider.findById(member.getId());
        // 密码正则
        String pwdRegex = "^(.*){6,20}$";

        if (StringUtils.isBlank(pass1)) {
            return Message.error("新密码不能为空！");
        }
        String realpwd = "";
        if(type.equals("safe")){
            realpwd = member.getLogin_password();
        }
        if(type.equals("deal")){
            realpwd = member.getPayment_password();
        }
        if (StringUtils.isBlank(oldpass) || !StringUtils.equals(DigestUtils.md5Hex(oldpass),
                realpwd )) {
            return Message.error("原密码输入不正确");
        }


        if (!StringUtils.equals(pass1, pass2)) {
            return Message.error("两次输入的密码不一致！");
        }

        if (!pass1.matches(pwdRegex)) {
            return Message.error("密码必须6-20位");
        }
        if(type.equals("safe")){
            member.setLogin_password(DigestUtils.md5Hex(pass1));
        }
        if(type.equals("deal")){
            member.setPayment_password(DigestUtils.md5Hex(pass1));
        }
        member.setUp_time(String.valueOf(System.currentTimeMillis()));
        member.setUp_ip(AppContext.getRemoteIp());
        memberProvider.updateById(member);
        if(type.equals("safe")){
            AppContext.removeAttribute(Constants.PRINCIPAL_SESSION_NAME);
            return Message.success("密码重置成功，请重新登陆！");
        }
        if(type.equals("deal")){
            member.setPayment_password(DigestUtils.md5Hex(pass1));

        }
        return Message.success("密码重置成功");

    }


    /**
     * 我的账户
     */
    @RequestMapping({"/safecenter"})
    public String safecenter(Model model) {
        Member user = getCurrentUser();
        Auth realName = certificationProvider.findByUserId(user.getId());
        model.addAttribute("realName", realName);
        model.addAttribute("member", user);
        return "wap/me/safecenter";
    }
    @RequestMapping({ "/ucenter/pwd/{type}" })
    public String pwd(HttpServletRequest request, @PathVariable String type)
            throws IllegalAccessException, InvocationTargetException,
            IntrospectionException, IOException {
        request.setAttribute("type", type);
        return "/wap/me/pwd";
    }

    /**
     * 申请实名认证
     */
    @RequestMapping("/auth/certification")
    @ResponseBody
    public Message certification(HttpServletRequest request, HttpSession session
            , @RequestParam("real_name") String real_name
            , @RequestParam("idnumber") String idnumber

    ) {
        Auth	realName = new Auth();
        Member user = getCurrentUser();
        try {
            int other = certificationProvider.findOther(idnumber, user.getId());
            if(other>0){
                throw  new NoticeException("同一张身份证在本平台不能注册2次");
            }



            realName.setUser_id(user.getId());
            realName.setReal_name(real_name);
            realName.setId_number(idnumber);
            realName.setAddtime(MsDateUtils.getTime());
            realName.setAddip(AppContext.getRemoteIp());
            realName.setStatus(0);
            String birthday;

            int sex = 0;

            if(idnumber.length()==15){
                birthday=idnumber.substring(6,12);


            }else if(idnumber.length()==18){
                birthday=idnumber.substring(6,14);
            }else{
                throw  new NoticeException("身份证有误");
            }

            if (idnumber.length() == 15 || idnumber.length() == 18)
            {
                String lastValue = idnumber.substring(idnumber.length() - 1, idnumber.length());

                if (lastValue.trim().toLowerCase().equals("x")||lastValue.trim().toLowerCase().equals("e"))
                {
                    sex = 0;
                }
                else
                {
                    sex = Integer.parseInt(lastValue) % 2;

                }
            }
            realName.setSex(sex);
            realName.setBirthdate(birthday);//生日奖励发放



            if(idCardQueryProvider.idCardQuery(idnumber,real_name)){



                realName.setStatus(1);

                certificationProvider.insert(realName);
            }else{
                realName.setStatus(0);



            }
        } catch (NoticeException e) {
            realName.setStatus(0);
        }
        catch (Exception e) {
            logger.error(e);
            return Message.success("出现未知错误");
        }
            if(certificationProvider.findByUserId(user.getId())!=null){
                realName.setId(certificationProvider.findByUserId(user.getId()).getId());
                certificationProvider.update(realName);
            }else{
                certificationProvider.insert(realName);
            }



        if(realName.getStatus()==1)
            return Message.success("认证成功");
        return Message.error("身份证错误");

    }

    /**
     * 我的账户
     */
    @RequestMapping({"/auth"})
    public String auth(Model model) {
        Member user = getCurrentUser();
        if (user != null) {
            Auth realName = certificationProvider.findByUserId(user.getId());
            model.addAttribute("auth", realName);
        }
        return "wap/me/auth";

    }
    /**
     * 我的账户
     */
    @RequestMapping({"/bankbind"})
    public String bank(Model model) {
        Member user = getCurrentUser();
        AccountBank bank = bankService.findByUserId(user.getId());
        model.addAttribute("bankCard", bank);
        return "wap/me/bank";

    }
    /**
     * 我的账户
     */
    @RequestMapping({"/recharge"})
    public String recharge(Model model) {
        Member user = getCurrentUser();
        AccountBank bank = bankService.findByUserId(user.getId());
        Account account = account_Service.findByUserId(user.getId());
        model.addAttribute("bankCard", bank);
        model.addAttribute("account", account);
        return "wap/me/recharge";

    }

    /**
     * 保存银行卡
     */
    @RequestMapping(value = {"/save"},produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public Message bankSave(HttpServletRequest request, HttpSession session) throws Exception{
        Member user =getCurrentUser();
        AccountBank bankCardNo = bankService.findByUserId(user.getId());
        List<FuyouBank> list = fuyouProvider.getList();
        if(bankCardNo == null ){
            bankCardNo = new AccountBank();
            bankCardNo.setBank_code(request.getParameter("bank"));
            for(FuyouBank bank:list){
                if(bank.getBank_code().equals(request.getParameter("bank"))){
                    bankCardNo.setBank(bank.getBank_name());
                    bankCardNo.setBank_img_mobile(bank.getBank_img_mobile());
                }
            }
            bankCardNo.setProvince(request.getParameter("s_province"));
            bankCardNo.setCity(request.getParameter("s_city"));
            bankCardNo.setArea(request.getParameter("s_county"));
            bankCardNo.setBranch(request.getParameter("branch"));
            bankCardNo.setBank_cardno(request.getParameter("bank_cardno"));
            bankCardNo.setUser_id(user.getId());
            bankCardNo.setAddtime(MsDateUtils.getTime());
            bankCardNo.setAddip(AppContext.getRemoteIp());
            bankCardNo.setStatus(1);
            bankService.insert(bankCardNo);
        }
        return Message.success("保存成功");
    }

    /**
     * 用BASE64加密
     *
     * @param str
     * @return
     */
    public static String getBASE64(String str) {
        byte[] b = str.getBytes();
        String s = null;
        if (b != null) {
            s = new sun.misc.BASE64Encoder().encode(b);
        }
        return s;
    }
    /**
     * 解密BASE64字窜
     *
     * @param s
     * @return
     */
    public static String getFromBASE64(String s) {
        byte[] b = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                return new String(b);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new String(b);
    }


}
